package com.imu.wys.servlet;

import com.imu.wys.dao.UserDao;
import com.imu.wys.dao.UserLogDao;
import com.imu.wys.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("*.UserAction")
public class UserServlet extends javax.servlet.http.HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String actionUrl = request.getServletPath(); // 获取用户请求的路径
        System.out.println(actionUrl);
        UserDao userDao = new UserDao();
        UserLogDao userLogDao = new UserLogDao();
        HttpSession session = request.getSession();
        if (actionUrl.equals("/login.UserAction")) {//登录模块
            String username = request.getParameter("username");
            String password= request.getParameter("password");
            User user = userDao.searchOne("select * from j1_user where username = '"+username+"'");
            if(user!=null){//用户存在
                if(user.getPassword().equals(password)){//成功
                    userLogDao.add(user,"登录");
                    session.setAttribute("user",user);
                    response.sendRedirect("main.jsp");
                }else {//密码错误
                    request.setAttribute("message","密码错误");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);
                }

            }else {//用户不存在
                request.setAttribute("message","用户名不存在");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }else if(actionUrl.equals("/drop.UserAction")){ //退出登录模块
            session.removeAttribute("user");
            request.setAttribute("message","退出登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
}
